<template>
<div class="container">
  <div class="left">
    <div class="top">
      <div class="terminal">
        <span>主控点</span>
        <el-select v-model="masterControlId" placeholder="请选择"
          @change="changeTerminal">
          <el-option
            v-for="(item, index) in terminalList"
            :key="index"
            :label="item.name"
            :value="item.masterControlId">
          </el-option>
        </el-select>
      </div>
      <div class="buttons">
        <el-button type="primary" @click="clickSetting">目标值设置</el-button>
        <el-date-picker
          v-model="date"
          style="width: auto;"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeDate">
        </el-date-picker>
      </div>
    </div>

    <div class="echarts" ref="e1" style="width: 100%; height: 200px;"></div>
    <div class="echarts" ref="e2" style="width: 100%; height: 200px;"></div>

    <el-table
      ref="singleTable"
      :data="levels"
      style="width: 100%"
      height="350"
      highlight-current-row
      @current-change="handleCurrentChange">
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="time"
        label="时间"
        sortable
        width="180">
      </el-table-column>
      <el-table-column
        prop="real"
        label="实测值（MPa）"
        sortable
        width="180">
      </el-table-column>
      <el-table-column
        prop="result"
        label="对比值（MPa）">
      </el-table-column>
      <el-table-column
        prop="level"
        label="等级">
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :modal="false">
      <Dialog
        @close="dialogVisible = false"
        @save="clickTargetSave"
        @changeHistoryDate="changeHistoryDate"
        :historyData="historyData" />
    </el-dialog>
  </div>
  <Side slot="side" :outsideAddress="terminalName" />
</div>
</template>

<script>
import echarts from 'echarts/lib/echarts'
import Dialog from '../../components/SolutionAssessment/Dialog'

const { ymd } = require('../../utils.js')
import Side from '../Monitor/Side'

let myChart = null
let hasClickMark = false // 是否点击过不同的主控点

export default {
  components: {
    Dialog,
    Side,
  },
  data() {
    return {
      startTime: null,
      endTime: null,
      target: {},
      real: {},
      date: '', // 日期
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      historyData: [],
      dialogVisible: false,
      // 主控点列表数据
      terminalList: [],
      terminalName: '',
      masterControlId: '',
      currentRow: null, // 当前列
    }
  },
  computed: {
    reqData() {
      return {
        startTime: this.startTime,
        endTime: this.endTime,
        masterControlId: this.masterControlId,
      }
    },
    levels() {
      let levels = []
      if(!this.real.targets || !this.target.targets.length) return levels
      // this.real.targets.forEach((r, i) => {
      const rts = this.real.targets
      for(let i = -1; ++i < rts.length;) {
        const r = rts[i]
        const rt = r.realValue
        // 如果真实值长度大于目标值则跳出
        if(i >= this.target.targets.length) break
        const result = Math.abs(r.realValue - this.target.targets[i].target)
        const time = r.time
        const real = rt
        const currentHours = new Date().getHours()
        const isNight = currentHours > 22 && currentHours < 8
        const [k1, k2, k3, k4] = [0.8, 2, 3.5, 10]
        const [n1, n2, n3, n4] = [1.2, 4.3, 7.5, 10]
        let level = 2 // 默认或错误等级

        if(isNight) {
          if(result >= 0 && result < k1) level = 4
          else if(result >= k1 && result < k2) level = 3
          else if(result >= k2 && result < k3) level = 2
          else if(result >= k3 && result < k4) level = 1
          else level = 2
        }else {
          if(result >= 0 && result < n1) level = 4
          else if(result >= n1 && result < n2) level = 3
          else if(result >= n2 && result < n3) level = 2
          else if(result >= n3 && result < n4) level = 1
          else level = 2
        }
        levels.push({
          level,
          result: result.toFixed(2),
          time,
          real,
        })
      }
      // console.log({levels})
      return levels
    },
  },
  mounted() {
    this.getTerminalList()
  },
  methods: {
    // 弹出框的修改历史日期事件
    changeHistoryDate(payload) {
      this.getHistoryData(payload)
    },
    // 日期改变
    changeDate(dates) {
      const startTime = dates[0]
      const endTime = dates[1]
      this.startTime = ymd(startTime)
      this.endTime = ymd(endTime)
      this.displayEcharts()
    },
    dateSelect(date) {
      console.log({date: date.getTime()})
    },
    // 点击目标值设置的保存
    clickTargetSave(payload) {
      console.log(payload)
      this.$post({
        url: '/dispatch/masterControlPoint/pressure/target',
        data: {
          masterControlId: this.masterControlId,
          name: this.terminalName,
          targets: payload.targets.map(t => ({
            ...t,
            somedayTargets: t.somedayTargets.map(st => ({
              ...st,
              target: parseFloat(st.target)
            }))
          })),
        }
      }).then(res => {
        if(!res) return

        // console.log({res})
        this.dialogVisible = false
        this.displayEcharts()
      })
    },
    // 获取历史目标值，弹出框内部
    getHistoryData({ startTime, endTime } = {}) {
      this.historyData = []
      this.$get({
        url: '/dispatch/masterControlPoint/pressure/target/history',
        params: {
          masterControlId: this.masterControlId,
          startTime,
          endTime,
        }
      }).then(data => {
        if(!data) return
        // console.log({data})
        this.historyData = data.targets.map(i => ({ ...i, time: `${new Date(i.startTime).getHours()}:00-${new Date(i.endTime).getHours()}:00`}))
      })
    },
    clickSetting() {
      this.dialogVisible = true
      this.getHistoryData()
    },
    getTerminalList() {
      this.$get({
        url: '/dispatch/masterControlPoint/info'
      }).then(data => {
        if(!data) return
        this.terminalList = data
        this.masterControlId = data[0].masterControlId
        setTimeout(() => {
          if(hasClickMark) return
          this.terminalName = data[0].name
          console.log('engine')
        }, 10000);
        this.displayEcharts()
      })
    },
    // 获取表格数据
    getTableData() {
      this.$get({
        url: '/dispatch/masterControlPoint/pressure/target/table',
        params: this.reqData
      }).then(res => {
        console.log({res})
      })
    },
    // 初始化 Echarts
    displayEcharts() {
      this.$fetchAll([
        this.$get({
          url: '/dispatch/masterControlPoint/pressure/real',
          params: this.reqData
        }),
        this.$get({
          url: '/dispatch/masterControlPoint/pressure/target/curve',
          params: this.reqData
        })
      ]).then(datas => {
        if(!datas) return
        this.real = datas[0]
        this.target = datas[1]
        // console.log(this.real)
        // console.log(this.target)

        const times = this.target.targets.map(i => new Date(i.time).toLocaleString())
        const levels = this.levels.map(i => i.level)
        const reals = this.real.targets.map(i => i.realValue)
        const targets = this.target.targets.map(i => i.target)
        const e1 = this.$refs.e1
        myChart = echarts.init(e1)
        myChart.on('click', this.clickEcharts.bind(this))
        let option = {
          // title: {
          //   text: 'Step Line'
          // },
          // tooltip: {
          //   trigger: 'axis'
          // },
          tooltip: {
            trigger: 'axis',
            triggerOn: 'mousemove',
            axisPointer: {
              type: 'cross'
            }
          },
          legend: {
            // data: ['Step Start', 'Step Middle', 'Step End']
          },
          grid: {
            left: '10%',
            right: '10%',
            bottom: 10,
            top: 40,
            containLabel: true
          },
          xAxis: {
            name: '时间',
            type: 'category',
            data: times,
          },
          yAxis: {
            name: '压力（Mpa）',
            type: 'value'
          },
          series: [
            {
              // name: 'Step Start',
              type: 'line',
              step: 'start',
              data: reals,
            },
            {
              // name: '高度(km)与气温(°C)变化关系',
              type: 'line',
              smooth: true,
              itemStyle: {
                normal: {
                  lineStyle: {
                    shadowColor: 'rgba(0,0,0,0.4)'
                  }
                }
              },
              data: targets,
              markPoint: {
                data: [
                  {
                    name: '最大值',
                    type: 'max'
                  },
                  {
                    name: '最小值',
                    type: 'min'
                  }
                ]
              }
            }
          ]
        }
        myChart.setOption(option, true)
        const e2 = this.$refs.e2
        myChart = echarts.init(e2)
        myChart.on('click', this.clickEcharts.bind(this))
        option = {
          tooltip: {
            trigger: 'axis',
            triggerOn: 'mousemove',
            axisPointer: {
              type: 'cross'
            }
          },
          grid: {
            left: '10%',
            right: '10%',
            bottom: 10,
            top: 40,
            containLabel: true
          },
          xAxis: {
            name: '时间',
            type: 'category',
            data: times,
          },
          yAxis: {
            name: '等级',
            type: 'value'
          },
          series: [
            {
              type: 'line',
              step: 'start',
              data: levels,
            }
          ]
        }
        myChart.setOption(option, true)
      })
    },
    // 点击 Echarts 表格事件
    clickEcharts(params) {
      // console.log(params)
      const i = params.dataIndex
      // console.log(this.tableData[i])
      this.$refs.singleTable.setCurrentRow(this.levels[i])
      this.$refs.singleTable.bodyWrapper.scrollTop = 47 * i
    },
    handleCurrentChange(val) {
      this.currentRow = val
    },
    changeTerminal(e) {
      this.hasClickMark = true
      // console.log(e)
      this.terminalName = this.terminalList.find(i => i.masterControlId === e).name
      this.displayEcharts()
    },
    formatter(row, column) {
      return row.address
    }
  }
}
</script>

<style scoped lang="less">
.container {
  display: flex;
  width: 100%;
}
.left {
  width: e('calc(100% - 300px)');
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .terminal {
    display: flex;
    align-items: center;
  }
}
</style>
